<template>
  <div id="work-box" ref="workBox">
    <h1 class="title">应用管理</h1>
    <div class="main-cont">
      <v-toolbar @click="handleClick"></v-toolbar>
      <div class="table-cont mt10">
        <el-table :data="tableData" :height="height">
          <el-table-column label="应用图标">
            <template slot-scope="scope">
              <img :src="scope.row.ImageUrl" />
            </template>
          </el-table-column>
          <el-table-column prop="Title" label="应用名称"></el-table-column>
          <el-table-column prop="Types" label="应用类型"></el-table-column>
          <el-table-column prop="createdTime" label="创建日期">
            <template slot-scope="scope">
              <span> {{ getLocalDate(scope.row.Created) }} </span>
            </template>
          </el-table-column>
          <el-table-column prop="AppUrl" label="应用包路径"></el-table-column>
          <el-table-column label="设置" width="200">
            <template slot-scope="scope">
              <el-button type="text" size="mini" @click="modifyApp(scope.row)">修改</el-button>
              <el-button type="text" size="mini" @click="delApp(scope.row)">删除</el-button>
              <el-button v-if="scope.row.AppUrl" type="text" size="mini" @click="handleUpData(scope.row)">更新包</el-button>
            </template>
          </el-table-column>
          <!-- <el-table-column :render-header="renderHeader" width="80">
              <template slot-scope="scope" v-if="scope.row.AppUrl">
                  <el-checkbox v-model="scope.row.checkedItem" @change="handleCheckBox(scope.row)"></el-checkbox>
              </template>
          </el-table-column> -->
        </el-table>
      </div>
    </div>
    <!-- 下面放会话框弹框 -->
    <v-dialog
      :title="editMode === 'ADD' ? '新建应用' : '修改应用' "
      :isVisible="dialogFormVisible"
      @close="closeDialog">
      <template slot="dialog-cont">
        <el-form :model="appForm" :rules="rules" ref="appForm" label-position="top" class="dialog-main dialogForm">
          <el-row :gutter="24">
            <el-col :span="12">
              <el-form-item label="应用名称" prop="Title">
                <el-input v-model="appForm.Title" placeholder="请输入应用名称"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="应用描述" prop="Description">
                <el-input v-model="appForm.Description"  placeholder="请输入应用描述"/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24">
            <el-col :span="12">
              <el-form-item label="应用类别" prop="Type">
                <el-select popper-class="zIndex-popper" v-model="appForm.Type" placeholder="请选择应用类别">
                  <el-option label="请选择" value=""></el-option>
                  <el-option label="H5应用" value="H"></el-option>
                  <el-option label="轻应用" value="Q"></el-option>
                  <el-option label="视图应用" value="V"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="引用标识" prop="RefId">
                <el-input v-model="appForm.RefId"  placeholder="请输入引用标识"/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24">
            <el-col :span="12">
              <el-form-item label="应用分类" prop="ClassifyList">
                <el-checkbox-group v-model="appForm.ClassifyList">
                  <el-checkbox v-for="item in ClassifyLists" :label="item.Name" :key="item.Name">{{item.Name}}</el-checkbox>
                </el-checkbox-group>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="是否登录" prop="IsLogin">
                <el-checkbox v-model="appForm.IsLogin" true-label="1" false-label="0">需要登录</el-checkbox>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24">
            <el-col :span="12">
              <el-form-item label="适用系统" prop="ClientsType">
                <el-select popper-class="zIndex-popper" v-model="appForm.ClientsType" placeholder="请选择适用系统">
                  <el-option label="全部" value="0"></el-option>
                  <el-option label="安卓" value="1"></el-option>
                  <el-option label="苹果" value="2"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <template v-if="appForm.Type === 'H' || appForm.Type === 'Q'">
                <el-form-item label="应用链接" prop="Url">
                  <el-input v-model="appForm.Url"  placeholder="请输入应用链接"/>
                </el-form-item>
              </template>
              <template v-else-if="appForm.Type === 'V'">
                <el-form-item label="布局视图" prop="ContentLayoutId" v-if="appForm.Type === 'V'">
                  <el-select popper-class="zIndex-popper" v-model="appForm.ContentLayoutId" placeholder="请选择布局视图">
                    <el-option v-for="item in LayoutLists" :key="item.Id" :label="item.Title" :value="item.Id"></el-option>
                  </el-select>
                </el-form-item>
              </template>
            </el-col>
          </el-row>
          <el-row :gutter="24" v-if="appForm.Type === 'Q'">
            <el-col :span="12">
              <el-form-item label="应用上传" prop="AppUrl">
                <v-upload title="选择应用上传" type="app" showType="w" :picUrl="appForm.AppUrl" @change="handlePicChange"></v-upload>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24">
            <el-col :span="12">
              <el-form-item label="应用图标" prop="ImageUrl">
                <v-upload title="选择应用图标" type="icon" :picUrl="appForm.ImageUrl" @change="handlePicChange"></v-upload>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </template>
      <template slot="dialog-btns">
        <div class="form-buttons">
          <el-button @click="resetForm" size="mini">重置</el-button>
          <el-button @click="closeDialog" size="mini">关闭</el-button>
          <el-button type="primary" @click="submitForm('appForm')" size="mini">确定</el-button>
        </div>
      </template>
    </v-dialog>
    <v-pic-select
    title="更新包"
    :isShow="isPackgageShow"
    @close="closeUpdateDialog">
    </v-pic-select>
  </div>
</template>
<script>
  import VToolbar from '../../comm/iToolbar/iToolbar'
  import VDialog from '../../comm/iDialog/iDialog'
  import VUpload from '../../comm/iUpload/iUpload'
  import VPicSelect from '../../comm/iPicSelect/iPicSelect'
  import ajax from '../../../../api/ajax/ajax'
  import { nextPage } from '../../../../assets/js'
  import api from '../../../../api/url'
  export default {
    components: {
      VToolbar,
      VDialog,
      VUpload,
      VPicSelect
    },
    data () {
      let validatorUrl = (rule, value, callback) => {
        if (this.appForm.Type === 'H' || this.appForm.Type === 'Q') {
          if (value === '') {
            callback(new Error('请输入应用链接'))
          } else {
            callback()
          }
        } else {
          callback()
        }
      }
      let validatorAppUrl = (rule, value, callback) => {
        if (this.appForm.Type === 'Q') {
          if (value === '') {
            callback(new Error('请选择应用上传'))
          } else {
            callback()
          }
        } else {
          callback()
        }
      }
      let validatorContentLayoutId = (rule, value, callback) => {
        if (this.appForm.Type === 'V') {
          if (value === '') {
            callback(new Error('请选择布局视图'))
          } else {
            callback()
          }
        } else {
          callback()
        }
      }
      return {
        // folderUrl: '', // 当前文件夹路径
        batchUpData: [], // 批量更新的数据标识
        UpDataContent: {}, // 跟新包的内容
        isSelect: null, // 是否是图标图片选择
        ClassifyLists: [], // 应用分类选项列表
        LayoutLists: [], // 布局视图的下拉列表
        isPackgageShow: false, // 选择图标会话框--标识
        ImageTableData: [], // 图标弹框列表
        appForm: {
          Title: '', // 应用名称
          ClassifyList: [], // 应用分类[AJAX时是数组]
          ImageUrl: '', // 应用图标
          Type: '', // 应用分类
          Description: '', // 应用描述
          ClientsType: '', // 使用系统
          RefId: '', // 引用标识
          IsLogin: '', // 是否需要登录
          Url: '', // 应用连接
          AppUrl: '', // 应用上传
          ContentLayoutId: '' // 视图应用中布局视图
        },
        createTime: '',
        appData: {},
        rules: {
          Title: [{ required: true, message: '请输入应用名称', trigger: 'blur' }],
          ImageUrl: [{ required: true, message: '请选择应用图标', trigger: 'blur' }],
          ClassifyList: [{ required: true, message: '请选择应用分类', trigger: 'blur' }],
          Type: [{ required: true, message: '请选择应用类别', trigger: 'blur' }],
          Url: [{ required: true, validator: validatorUrl, trigger: 'blur' }],
          AppUrl: [{ validator: validatorAppUrl, required: true, trigger: 'blur' }],
          ContentLayoutId: [{ required: true, validator: validatorContentLayoutId, trigger: 'blur' }]
        },
        editMode: 'ADD', // 是否-新增-修改
        dialogFormVisible: false, // 新增修改标识会话框
        tableData: [], // 首页表格数据
        checkedArr: [],
        height: null
      }
    },
    methods: {
      // 工具栏--按钮
      handleClick (val) {
        switch (val) {
          case 'add':
            this.addApp()
            break
          default:
            break
        }
      },
      // 查询应用列表
      queryAppList () {
        ajax.get(api.QUERY_APP_LIST).then(res => {
          if (res.Message === 'Success.') {
            if (res.Apps && res.Apps.length > 0) {
              this.tableData = res.Apps.map(item => {
                // 过滤应用类型
                if (item.Type === 'H') {
                  item.Types = 'H5应用'
                } else if (item.Type === 'Q') {
                  item.Types = '轻应用'
                  item.checkedItem = ''
                } else if (item.Type === 'V') {
                  item.Types = '视图应用'
                }
                return item
              })
            }
          }
        })
      },
      // 应用分类列表查询
      queryClassifyLists () {
        ajax.get(api.QUERY_DICTIONARY_DETAILS, {dictionaryid: 'AppClassify'}).then(res => {
          if (res && res.length > 0) {
            this.ClassifyLists = res
          } else {
            this.$confirm('暂无应用分类，部分操作将不能实现，是否前去添加应用分类？', '温馨提示', {
              cancelButtonText: '取消',
              confirmButtonText: '确定',
              type: 'warning'
            }).then(res => {
              nextPage('/home/cateSetting')
            }).catch(() => {
              this.$message({
                type: 'info',
                message: '已取消操作'
              })
            })
          }
        }).catch((err) => {
          console.info(err)
        })
      },
      // 布局视图下拉列表查询
      queryLayoutLists () {
        ajax.get(api.QUERY_LAYOUT_LIST).then(res => {
          this.LayoutLists = res
        })
      },
      // 新增应用
      addApp () {
        this.editMode = 'ADD'
        this.dialogFormVisible = true
      },
      // 修改应用
      modifyApp (data) {
        this.dialogFormVisible = true
        this.editMode = 'EDIT'
        this.appForm.Description = data.Description
        this.appForm.ImageUrl = data.ImageUrl
        this.appForm.RefId = data.RefId
        this.appForm.Title = data.Title
        this.appForm.Type = data.Type
        this.appForm.Url = data.Url
        this.appForm.IsLogin = data.IsLogin
        this.appForm.ClientsType = data.ClientsType
        if (data.ClassifyList[0].Id === 1) {
          this.appForm.ClassifyList = this.ClassifyLists.map(item => item.Name)
        }
        this.appForm.Id = data.Id
        if (data.ContentLayoutId) {
          this.appForm.ContentLayoutId = data.ContentLayoutId
        }
        this.appForm.AppUrl = data.AppUrl ? data.AppUrl : ''
        this.createTime = data.Created
        this.appData = JSON.parse(JSON.stringify(data))
      },
      // 处理图片选择
      handlePicChange (data) {
        switch (data.type) {
          case 'icon':
            this.appForm.ImageUrl = data.url
            break
          case 'app':
            this.appForm.AppUrl = data.url
            break
          default:
            break
        }
      },
      // 删除应用
      delApp (data) {
        this.$confirm('是否确定删除?', '温馨提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let params = { id: data.Id }
          ajax.get(api.APP_DELETE, params)
            .then(res => {
              if (res.Message === 'Success.') {
                this.queryAppList()
                this.$message({
                  type: 'success',
                  message: '删除成功!'
                })
              }
            })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
      },
      // 更新包
      handleUpData (data) {
        this.isSelect = 'UPDATA'
        this.UpDataContent = JSON.parse(JSON.stringify(data))
        this.isPackgageShow = true
      },
      // 确定更新
      handleUpDataConfirm (oprType) {
        if (this.isSelect === 'UPDATA') {
          let params = {
            AppUrl: this.UpDataContent.AppUrl,
            ClassifyList: [{Id: 1}],
            ClientsType: this.UpDataContent.ClientsType,
            Created: this.UpDataContent.Created,
            Description: this.UpDataContent.Description === undefined ? '' : this.UpDataContent.RefId,
            Id: this.UpDataContent.Id,
            ImageUrl: this.UpDataContent.ImageUrl,
            IsLogin: this.UpDataContent.IsLogin,
            RefId: this.UpDataContent.RefId === undefined ? '' : this.UpDataContent.RefId,
            Title: this.UpDataContent.Title,
            Type: this.UpDataContent.Type,
            Url: this.UpDataContent.Url
          }
          ajax.post(api.APP_UP_DATA, params)
            .then(res => {
              if (res.Message === 'Success.') {
                this.isPackgageShow = false
                this.queryAppList()
                this.$message({
                  message: '更新应用成功',
                  type: 'success'
                })
              } else {
                this.$message.error('修改应用失败')
              }
            })
        } else if (this.isSelect === 'BATCH') {
          let data = {
            selectIds: this.batchUpData.toString(),
            dir: this.UpDataContent.AppUrl
          }
          ajax.post(api.APP_LIST_UP_DATE, data)
            .then(res => {
              if (res.Message === 'Success.') {
                this.isPackgageShow = false
                this.queryAppList()
                this.$message({
                  message: '应用包批量更新成功',
                  type: 'success'
                })
              }
            })
        } else {}
      },
      handleCheckBox (data) {
        if (data.checkedItem === true) {
          let flag = this.batchUpData.filter(item => item === data.Id)
          if (flag.length < 1) {
            this.batchUpData.push(data.Id)
          }
        } else {
          this.batchUpData.forEach((item, index) => {
            if (item === data.Id) {
              this.batchUpData.splice(index, 1)
            }
          })
        }
      },
      // 提交表单(新增/修改)
      submitForm (formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            this.handleSubmitFormConfirm()
          } else {
            return false
          }
        })
      },
      // 提交到后台(新增/修改)
      handleSubmitFormConfirm () {
        let params = JSON.parse(JSON.stringify(this.appForm))
        if (params.ClassifyList.length) {
          params.ClassifyList = [{Id: 1}]
        }
        if (params.Type === 'V') {
          params.Url = ''
        } else if (params.Type === 'Q') {
          delete params.ContentLayoutId
        } else {
          params.AppUrl = ''
          delete params.ContentLayoutId
        }
        /* if (params.AppUrl !== undefined && params.AppUrl !== '') {
          params.AppUrl = params.AppUrl.slice(1, params.AppUrl.length - 1)
        } */
        // 应用新增
        if (this.editMode === 'ADD') {
          ajax.post(api.APP_CREATE, params).then(res => {
            if (res.Message === 'Success.') {
              this.closeDialog()
              this.queryAppList()
              this.$message({
                message: '新增应用成功',
                type: 'success'
              })
            } else {
              this.$message.error('新增应用失败')
            }
          })
        }
        // 应用修改
        if (this.editMode === 'EDIT') {
          params.Created = parseInt(this.createTime)
          ajax.post(api.APP_UP_DATA, params)
            .then(res => {
              if (res.Message === 'Success.') {
                this.closeDialog()
                this.queryAppList()
                this.$message({
                  message: '修改应用成功',
                  type: 'success'
                })
              } else {
                this.$message.error('修改应用失败')
              }
            })
        }
      },
      // 关闭新增/修改应用弹窗
      closeDialog () {
        this.initForm('appForm')
        this.dialogFormVisible = false
      },
      // 关闭更新包弹窗
      closeUpdateDialog (data) {
        if (data !== '') {
          this.UpDataContent.AppUrl = data
          this.$confirm('确定要更新包吗？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.handleUpDataConfirm()
          }).catch(() => {
            this.$message({
              type: 'info',
              message: '已取消删除'
            })
          })
        }
        this.isPackgageShow = false
      },
      // 初始化表单
      initForm (formName) {
        this.$refs[formName].resetFields()
        this.appForm.Title = ''
        this.appForm.ClassifyList = []
        this.appForm.ImageUrl = ''
        this.appForm.Type = ''
        this.appForm.Description = ''
        this.appForm.ClientsType = ''
        this.appForm.RefId = ''
        this.appForm.IsLogin = ''
        this.appForm.AppUrl = ''
        this.appForm.Url = ''
        this.appForm.ContentLayoutId = ''
      },
      // 重置
      resetForm () {
        this.initForm('appForm')
        if (this.editMode === 'EDIT') {
          this.appForm = { ...this.appData }
          if (this.appForm.ClassifyList[0].Id === 1) {
            this.appForm.ClassifyList = this.ClassifyLists.map(item => item.Name)
          }
        }
      },
      // 时间戳转换
      getLocalDate (timestamp) {
        /* let newDate = new Date()
        newDate.setTime(timestamp * 1000) //  + newDate.toLocaleTimeString() 具体时间
        return newDate.toLocaleDateString() */
        let date = new Date(timestamp * 1000).toLocaleString().split(' ')[0]
        return date
      }
      // 批量处理
      /* renderHeader (h, data) {
        return h('el-button', {
          attrs: {
            type: 'text',
            size: 'mini'
          },
          on: {
            click: () => {
              if (this.batchUpData.length <= 0) {
                this.$alert('请选择要更新的应用', '温馨提示', {confirmButtonText: '确定'})
                return
              } else if (this.batchUpData.length === 1) {
                this.$alert('请至少选择两条要更新的应用', '温馨提示', {confirmButtonText: '确定'})
                return
              }
              this.isSelect = 'BATCH'
              // this.folderUrl = ''
              this.isPackgageShow = true
            }
          }
        }, ['批量更新'])
      } */
    },
    created () {
      this.queryAppList()
      this.queryClassifyLists()
      this.queryLayoutLists()
      this.$nextTick(() => {
        this.height = this.$refs.workBox.offsetHeight - 138
      })
    }
  }
</script>
<style lang="stylus">
  #work-box
    height 100%
    overflow hidden
    .checked
      display block
      margin-left 15px
      width 32px
      height 32px
      background url('') no-repeat center center
    .title
      height 60px
      padding 15px
      line-height 30px
      font-size 18px
      font-weight normal
      background #fff
    .mt10
      margin-top 10px
    .main-cont
      padding 10px 0 0 10px
    .table-cont
      img
        height:30px;
        max-width:50px
    .folder-url
      margin-left 10px
</style>
